package com.blog.filter;

import com.blog.pojo.Users;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;

@WebFilter(value = "*.jsp")
public class JspFilter implements Filter {

    static List<String> lists=new ArrayList<String>();

    /**
     * 存储的是所有的必须登录的资源
     */
    static {
        lists.add("/Blog/admin/add.jsp");
        lists.add("/Blog/admin/admin.jsp");
        lists.add("/Blog/admin/edit.jsp");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 完成过滤操作
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        //System.out.println(requestURI);
        Users users= (Users) request.getSession().getAttribute("user");
        if(users==null){
            //没有登录
            if(lists.contains(requestURI)){
                //访问的是必须登录的资源
                response.sendRedirect("/Blog/login.jsp");
            }else{
                filterChain.doFilter(request, response);//放行
            }
        }else{
            filterChain.doFilter(request, response);//放行
        }
    }

    @Override
    public void destroy() {

    }


}
